package com.kasax.test.bc.viewmodel

import androidx.lifecycle.ViewModel
import com.kasax.hilog.Logger
import com.kasax.utils.GsonUtils
import com.kasax.utils.ThreadUtils
import java.net.HttpURLConnection
import java.net.URL

class AndroidNetworkCompTestViewModel : ViewModel() {

    fun testGetIpAddrWithHttpUrlConnection() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL("https://cx.shouji.360.cn/phonearea.php?number=17688888888")
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "GET"
                openConnection.connect()

                if (openConnection.responseCode == HttpURLConnection.HTTP_OK) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    val dataJsonStr = GsonUtils.deEnconde(result.toString())
                    Logger.log("result: $dataJsonStr")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    fun getToabaiIpWithHttpUrlConnection() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL("https://ip.taobao.com/outGetIpInfo")
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "POST"
                openConnection.doOutput = true
                openConnection.doInput = true
                openConnection.useCaches = false
                openConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                val params = mutableMapOf<String, String>()
                params["accessKey"] = "alibaba-inc"
                params["ip"] = "11.11.11.11"
                openConnection.outputStream.bufferedWriter().use {
                    it.write(params.map { "${it.key}=${it.value}" }.joinToString("&"))
                }
                openConnection.connect()

                if (openConnection.responseCode == 200) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    fun getFormUrlWithHttpUrlConnection() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL("http://api.crap.cn/visitor/example/post.do")
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "POST"
                openConnection.doOutput = true
                openConnection.doInput = true
                openConnection.useCaches = false
                openConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                val params = mutableMapOf<String, String>()
                params["param"] = "测试22"
                params["email"] = "crap.cn@gmail.com"
                params["555"] = "我"
                openConnection.outputStream.bufferedWriter().use {
                    it.write(params.map { "${it.key}=${it.value}" }.joinToString("&"))
                }
                openConnection.connect()

                if (openConnection.responseCode == 200) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    fun getJsonParamWithHttpUrlConnection() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL("http://api.crap.cn/visitor/example/json.do")
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "POST"
                openConnection.doOutput = true
                openConnection.doInput = true
                openConnection.useCaches = false
                openConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8")

                openConnection.outputStream.bufferedWriter().use {
                    it.write("{\n" + "\"id\":\"8989-dddvdg\",\n" + "\"name\":\"文章标题-JSON格式参数演示\",\n" + "\"brief\":\"快速入门json参数\",\n" + "\"category\":\"分类\"\n" + "}")
                }
                openConnection.connect()

                if (openConnection.responseCode == 200) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    fun getXmlParamWithHttpUrlConnection() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL("http://api.crap.cn/visitor/example/xml.do")
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "POST"
                openConnection.doOutput = true
                openConnection.doInput = true
                openConnection.useCaches = false
                openConnection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8")
                openConnection.outputStream.bufferedWriter().use {
                    it.write(
                        "<users>\n" + "<name>用户名</name>\n" + "<value>value值</value>\n" + "</users>"
                    )
                }
                openConnection.connect()
                if (openConnection.responseCode == 200) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    val BANNER_URL: String = "https://www.wanandroid.com/banner/json"

    val LOGIN_URL: String = "https://www.wanandroid.com/user/login"
    fun testWanAndroidBanners() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL(BANNER_URL)
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "GET"
                openConnection.connect()

                if (openConnection.responseCode == HttpURLConnection.HTTP_OK) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }

    fun testWanAndroidLogin() {
        ThreadUtils.IO_EXECUTOR.execute {
            var openConnection: HttpURLConnection? = null
            try {
                val url: URL = URL(LOGIN_URL)
                openConnection = url.openConnection() as HttpURLConnection
                openConnection.readTimeout = 120 * 1000
                openConnection.connectTimeout = 120 * 1000
                openConnection.requestMethod = "POST"
                openConnection.doOutput = true
                openConnection.doInput = true
                openConnection.useCaches = false
                openConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
                val params = mutableMapOf<String, String>()
                params["username"] = "zzgtest02"
                params["password"] = "123456"

//            val buffer = StringBuilder()
//            params.forEach { buffer.append("${it.key}=${it.value}&") }
//            buffer.deleteCharAt(buffer.length - 1)
//            Logger.log("params: $buffer")
//            openConnection.outputStream.write(buffer.toString().toByteArray())

                val paramsStr = params.map { "${it.key}=${it.value}" }.joinToString("&")
                Logger.log("paramsStr: $paramsStr")
                openConnection.outputStream.bufferedWriter().use {
                    it.write(paramsStr)
                }

                openConnection.connect()

                if (openConnection.responseCode == 200) {
                    Logger.log("responseCode: ${openConnection.responseCode}")
                    val result = StringBuilder().apply {
                        openConnection.inputStream.bufferedReader().use {
                            it.lineSequence().forEach { line ->
                                append(line)
                            }
                        }
                    }
                    Logger.log("result: $result")
                }
            } catch (e: Exception) {
                Logger.log("error: ${e.message}")
            } finally {
                if (openConnection != null) {
                    openConnection.disconnect()
                }
            }
        }
    }
}